type Props = { drawerOpen: boolean; drawerToggle: (v: boolean) => void }
import { getAdvisorList } from '@/api'
import useAvatar from '@/hooks/useAvatar'
import { DefaultPagination, appDrawerWidth } from '@/store/constant'
import { AdvisorItem } from '@/types/common'

const ChatSidebar = ({ drawerOpen, drawerToggle }: Props) => {
  const theme = useTheme()
  const matchUpMd = useMediaQuery(theme.breakpoints.up('md'))
  const customization = useSelector((state: any) => state.customization)
  const ref = useRef<HTMLDivElement>(null)
  const PAGE_SIZE = DefaultPagination.pageSize
  const getLoadMoreList = async (page: number, pageSize: number) => {
    const res = await getAdvisorList({ page, size: pageSize })
    return res
      ? {
          list: (res.data ?? []).map((v) => ({ ...v, avatar: getRandom({ backgroundColor: 'EDE7F6' }) })),
          page: res.page,
          total: res.total
        }
      : undefined
  }

  const { data, loading, loadMore, loadingMore, noMore } = useInfiniteScroll(
    // @ts-ignore
    (d) => {
      const page = d ? d.page + 1 : 1
      return getLoadMoreList(page, PAGE_SIZE)
    },
    {
      target: ref,
      isNoMore: (d) => (d ? d.list.length >= d.total : undefined)
    }
  )
  const { getRandom } = useAvatar()

  return (
    <Box
      sx={{
        flexShrink: { md: 0 },
        width: matchUpMd ? appDrawerWidth : 'auto',
        position: 'relative',
        height: '100%',
        transition: 'transform 300ms cubic-bezier(0, 0, 0.2, 1) 0ms',
        ...(matchUpMd && { transform: { md: `translateX(${drawerOpen ? 0 : -1 * appDrawerWidth}px)` } })
      }}
      aria-label="chat sidebar"
    >
      <Drawer
        variant={matchUpMd ? 'persistent' : 'temporary'}
        anchor="left"
        open={drawerOpen}
        onClose={drawerToggle}
        sx={{
          '& .MuiDrawer-paper': {
            width: appDrawerWidth,
            background: theme.palette.background.paper,
            color: theme.palette.text.primary,
            borderRight: 'none',
            position: 'absolute',
            borderRadius: get(customization, ['borderRadius']) + 'px',
            padding: 2
          }
        }}
        ModalProps={{ keepMounted: true }}
        color="inherit"
      >
        <Box ref={ref} style={{ height: '100%', overflow: 'auto' }}>
          {loading ? (
            <Stack sx={{ width: '100%', height: '100%' }} direction="column" spacing={2}>
              {range(0, 9).map((v: number) => (
                <Skeleton key={v} variant="rounded" width="100%" height="8%"></Skeleton>
              ))}
            </Stack>
          ) : (
            <>
              <List>
                {(data?.list ?? []).map((advisor: AdvisorItem & { avatar: string }) => {
                  return (
                    <ListItem
                      key={advisor.advisor_id}
                      sx={{
                        borderBottom: `1px solid ${theme.palette.grey[200]}`,
                        ':hover': {
                          bgcolor: 'secondary.light'
                        }
                      }}
                    >
                      <ListItemAvatar>
                        <Avatar sx={{ backgroundColor: 'secondary.light' }} src={advisor.avatar}></Avatar>
                      </ListItemAvatar>
                      <ListItemText
                        primary={
                          <Typography
                            variant="body1"
                            fontSize=".875rem"
                            sx={{
                              fontWeight: 600,
                              mb: 0.25
                            }}
                          >
                            {advisor.name}
                          </Typography>
                        }
                        secondary={
                          <Typography
                            variant="body2"
                            fontSize=".75rem"
                            sx={{
                              color: 'text.secondary'
                            }}
                          >
                            {advisor.email}
                          </Typography>
                        }
                      ></ListItemText>
                    </ListItem>
                  )
                })}
              </List>
              <Box style={{ marginTop: 8, textAlign: 'center' }}>
                {!noMore && (
                  <Button type="button" onClick={loadMore} disabled={loadingMore}>
                    {loadingMore ? 'Loading more...' : 'Click to load more'}
                  </Button>
                )}
                {noMore && <Typography variant="body2">No more data</Typography>}
              </Box>
            </>
          )}
        </Box>
      </Drawer>
    </Box>
  )
}

export default ChatSidebar
